﻿using DataScripter.Excel.Formatters;
using DataScripter.Excel.Formulas;
using DataScripter.Excel.Functions;

namespace DataScripter.Excel.Table
{
	internal class TableColumn
	{
		public string ColumnName { get; private set; }
		public TableContent Table { get; set; }
		public int Index { get; set; }
		public string ColumnText { get; private set; }

		public ICellFormatter Formatter { get; set; }

		public int Column
		{
			get
			{
				if (Table.StartCell == null)
					return Index;
				return Table.StartCell.Column + Index;
			}
		}

		public TableColumn(TableContent table, string columnName)
		{
			Table = table;
			ColumnText = columnName;
			ColumnName = BuildColumnName(columnName);
			Formatter = new NoFormatter();
		}

		private string BuildColumnName(string columnName)
		{
			string[] parts = columnName.Split(' ');
			for (int index = 0; index < parts.Length; index++)
			{
				string part = parts[index]
								.Replace('#', '_')
								.Replace("(", "")
								.Replace(")", "")
								.Replace("?", "")
								;
				if(!string.IsNullOrEmpty(part))
				{
					parts[index] = part.Substring(0, 1).ToUpper() + part.Substring(1);
				}
			}
			return string.Join(string.Empty, parts);
		}

		public override string ToString()
		{
			return ColumnText;
		}

		public Formula Lookup2Ref(string lookupValue)
		{
			return new Lookup2Ref(lookupValue, this);
		}
		public Formula Lookup2Ref(int lookupValue)
		{
			return new Lookup2Ref(lookupValue, this);
		}
		public Formula Lookup(Formula toLookup)
		{
			return new Lookup(toLookup, Table.Table, Index + 1);
		}
		public Formula Lookup(ICell toLookup)
		{
			return new Lookup(toLookup, Table.Table, Index + 1);
		}

		public Formula Ref()
		{
			return new TableColumnReference(this);
		}
		public Formula Ref(int rowDiff)
		{
			return new TableColumnReference(this, rowDiff);
		}
		public Formula RefAbsoluteRow(int rowNr)
		{
			return new TableColumnReferenceAbsoluteRow(this, rowNr);
		}
		public Formula Last()
		{
			return new TableColumnReferenceAbsoluteRow(this, Table.Rows.Count);
		}

	}
}